package com.flow.framework.core.validation.validator.base;

import com.flow.framework.common.util.collection.CollectionUtil;
import com.flow.framework.common.util.verify.VerifyUtil;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.internal.engine.constraintvalidation.ConstraintValidatorContextImpl;
import org.hibernate.validator.internal.engine.constraintvalidation.ConstraintViolationCreationContext;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.lang.annotation.Annotation;
import java.util.List;

/**
 * 基础校验器
 *
 * @author luoguopiao
 * @version 0.0.1
 * @date 2022/1/22
 */
@Slf4j
public abstract class BaseValidator<A extends Annotation, T> implements ConstraintValidator<A, T> {

    /**
     * 记录错误日志
     *
     * @param context context
     * @param value value
     * @param extraMsg extraMsg
     */
    protected void logError(ConstraintValidatorContext context, Object value, String extraMsg) {
        if (context instanceof ConstraintValidatorContextImpl) {
            ConstraintValidatorContextImpl constraintValidatorContext = (ConstraintValidatorContextImpl) context;
            List<ConstraintViolationCreationContext> constraintViolationCreationContexts
                    = constraintValidatorContext.getConstraintViolationCreationContexts();
            if (!VerifyUtil.isEmpty(constraintViolationCreationContexts)) {
                log.error("accept error param. current value : {}, field : {}, " + extraMsg, value,
                        CollectionUtil.getFirstElement(constraintViolationCreationContexts).getPath().asString());
            }
        } else {
            if (!VerifyUtil.isEmpty(extraMsg)) {
                log.error(extraMsg);
            }
        }
    }
}